<template>
  <div>
    <el-dialog ref="dialog" :title="setTitle" :visible.sync="showDialog" width="50%" @close="closeDialog"  :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form @submit.native.prevent ref="form" :model="form" :rules="rules" size="small" label-position="right" label-width="110px" v-loading="init">
        <el-form-item :label="$root.lang.control.app.create.appName" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item :label="$root.lang.control.app.create.version" prop="version">
          <el-input v-model="form.version"></el-input>
        </el-form-item>
        <el-form-item :label="$root.lang.control.app.create.mainClass" prop="mainClass">
          <el-input v-model="form.mainClass"></el-input>
        </el-form-item>
        <el-form-item :label="$root.lang.control.app.create.file" prop="fileUrl">
          <el-input ref="fileInput" readonly v-model="form.fileUrl" @blur="changeFile('fileUrl')"></el-input>
          <el-upload
            ref="fileUrl"
            class="upload-demo"
            :action="$root.fileUpload"
            enctype="multipart/form-data"
            :headers=headers
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success="onsuccess"
            :before-remove="beforeRemove"
            multiple
            :limit="1"
            :on-exceed="handleExceed"
            :file-list="fileList">
            <el-button size="small" type="primary" style="margin-top: 10px;display: block;">{{ $root.lang.control.app.create.selectFile }}</el-button>
            <!-- <div slot="tip" class="el-upload__tip">只能上传文件，且不超过kb</div> -->
          </el-upload>
        </el-form-item>
        <el-form-item :label="$root.lang.control.app.create.remake" >
          <el-input type="textarea" v-model="form.remark"></el-input>
        </el-form-item>
        <el-form-item>
        <el-button class="dialog-btn"  type="primary" @click="onSubmit('form')">{{ $root.lang.control.app.create.confirm }}</el-button>
      </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      init: false,
      loading: false,
      fileList: [],
      ena: '',
      enb: '',
      enc: '',
      //文件id
      fileId: null,
      showDialog: this.show,
      editData: this.detail,
      headers: {
        accessToken: this.$store.getters.status
      },
      form: {
        name: '',
        version: '',
        mainClass: '',
        remark: '',
        fileUrl: '',
      },
      rules: {
        name: [{ required: true, message: this.$root.lang.control.app.create.rule.name, trigger: 'blur' }],
        version: [{ required: true, message: this.$root.lang.control.app.create.rule.version, trigger: 'blur' }],
        mainClass: [{ required: true, message: this.$root.lang.control.app.create.rule.mainClass, trigger: 'blur' }],
        fileUrl: [{ required: true, message: this.$root.lang.control.app.create.rule.file, trigger: 'blur' }],
      },
    }
  },
  props: {
    show: {
      type: Boolean,
      default: false
    },
    detail: {
      type: Object,
      default: null
    }
  },
  watch: {
    show: function (value) {
      if(this.$refs['form']) this.$refs['form'].resetFields()
      this.showDialog = value
    },
    detail: function (value) {
      console.log(value)
      this.form = value
    }
  },
  computed: {
    setTitle() {
      return (this.form.id) ?  this.$root.lang.control.app.create.editTitle : this.$root.lang.control.app.create.title
    }
  },
  methods: {
    closeDialog() {
      this.$emit('editReceive',{
        key: 'showEdit',
        value: this.showDialog
      })
    },
    handleRemove(file, fileList) {
        console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    changeFile(value) {
        this.$refs[value].clearFiles()
    },
    checkLang() {
      let langType = this.$root.getStorage('lang')
      if(langType == 'en') {
        this.ena = 'Currently, one file is restricted. This time, '
        this.enb = ' files are selected. A total of '
        this.enc = ' files are selected '
      } else {
        this.ena = '当前限制选择 1 个文件，本次选择了'
        this.enb = '个文件，共选择了'
        this.enc = '个文件'
      }
    },
    onsuccess(file) {
      console.log(file);
      this.form.fileUrl = file.result.url
      this.fileId = file.result.id
      this.$refs['fileInput'].focus()
    },
    handleExceed(files, fileList) {
      this.$message.warning(`${this.ena}${files.length}${this.enb}${files.length + fileList.length}${this.enc}`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`${this.$root.lang.control.app.create.cDelete} ${ file.name }？`);
    },
    onSubmit(formName) {
      let base = this
      var flag = true

      base.$refs[formName].validate((valid) => {
        if (!valid) {
          flag = false
          return false
        }
      })
      if(flag) {
        delete base.form['fileUrl']
        base.form.fileId = this.fileId
        if(base.form.id) base.doEdit()
        else base.doCreate()
      }
    },
    doCreate() {
      let base = this
      base.loading = true

      base.request({
        url: '/api/app/create',
        method: 'post',
        data: base.$root.optionProcess(base.form)
      }).then(response => {
        base.loading = false
        base.showDialog = false
        base.$emit('reload')
        base.$message({
          message: this.$root.lang.confirm.addSuccess,
          type: 'success',
          duration: 3 * 1000,
        })
      }).catch(error => {
        base.loading = false
        base.$message({
          message: error.errmsg,
          type: 'error',
          duration: 3 * 1000
        })
      })
    },
    doEdit() {
      let base = this
      base.loading = true
      console.log(base.form)
      base.request({
        url: '/api/app/update',
        method: 'post',
        data: base.form
      }).then(response => {
        base.loading = false
        this.showDialog = false
        this.$emit('reload')
        base.$message({
          message: this.$root.lang.confirm.editSuccess,
          type: 'success',
          duration: 3 * 1000,
        })
      }).catch(error => {
        base.loading = false
        base.$message({
          message: error.errmsg,
          type: 'error',
          duration: 3 * 1000
        })
      })
    },
  },
  created() {
    var lett = this;
    document.onkeydown = function(e) {
      var key = window.event.keyCode;
      var button = document.querySelector('.dialog-btn')
      if(!button) return
      if (key == 13) {
        lett.onSubmit('form')
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">

</style>